const fs = require("fs-extra");
const path = require("path");

const upperFirst = require("lodash/upperFirst");
const camelCase = require("lodash/camelCase");

const view_path = (pathname, name) =>
  path.resolve("src/views", pathname, `${name}.vue`);

const template_path = (name) => path.resolve("nil-cli/template", `${name}.vue`);
const component_path = path.resolve("src/components/nil");

const file_type = {
  空页面: "empty",
  列表页: "list",
};

function copyFile(type, target) {
  try {
    fs.copySync(template_path(type), target);
    console.log("文件创建成功....");
  } catch (error) {
    console.log(error);
    console.log("文件创建失败....");
  }
}

module.exports = {
  createViewFile(path, name, type) {
    const _path = view_path(path, name);
    console.log({ _path });
    try {
      fs.accessSync(_path);
      console.log("文件已存在");
    } catch (error) {
      // 文件不存在
      // 创建文件
      const _type = file_type[type];
      copyFile(_type, _path);
      console.log({ _type });
    }
  },
  createComponentType() {
    // 获取文件列表
    try {
      let list = fs.readdirSync(component_path);
      list = list.filter((it) => it.endsWith(".vue"));
      //

      const temp = (tttttt) => `declare module "@vue/runtime-core" {
  export interface GlobalComponents {${tttttt}
  }
}

export {};`;
      const tin = (cName, Name) =>
        `
    ${cName}: typeof import("@/components/nil/${Name}").default;
`;
      let _file_tin = ``;

      // aaaAppp.vue
      list.forEach((it) => {
        const its = it.split(".");
        its.pop();
        its.map((it) => upperFirst(it));
        const componentName = "Nil" + its.join("");
        _file_tin += tin(componentName, it);
      });

      fs.writeFileSync(
        path.resolve("src/types/nil.component.d.ts"),
        temp(_file_tin)
      );

      console.log("组件类型文件创建成功....");
    } catch (error) {
      console.log("组件类型文件创建失败....");
      console.log(error);
    }
  },
};
